package com.tedu.springhomework.controller;

import com.tedu.springhomework.entity.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.lang.reflect.Field;

@Controller
public class UserLogIn {

    @RequestMapping("/logUser")
    public void log(HttpServletRequest request, HttpServletResponse response) {
        String name = request.getParameter("name");
        String word = request.getParameter("word");

        if (name == null || name.trim().isEmpty() ||
                word == null || word.trim().isEmpty()) {
            try {
                response.sendRedirect("/user_name_wrong.html");
            } catch (IOException e) {
                e.printStackTrace();
            }
        }


        File file = new File(UserController.userDate,name + ".obj");

        try {
            if (file.exists()) {
                ObjectInputStream ois = new ObjectInputStream(
                        new FileInputStream("./users/" + name + ".obj"));
                User user = (User) ois.readObject();
                if (word.equals(user.getPassword())) {
                    response.sendRedirect("/log_success.html");
                    return;
                }
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        try {
            response.sendRedirect("/word_wrong.html");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }
}
